//
//  ConfirmServiceViewController.m
//  SsehMaster
//
//  Created by 杨阳 on 2018/8/11.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "ConfirmServiceViewController.h"
#import "LabelLabelTableViewCell.h"
#import "SelectdMateralModel.h"
#import "OrderInforModel.h"


@interface ConfirmServiceViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * ssehTableView;

@property (nonatomic,strong) UILabel * totlePrice;

@end

static NSString * const LabelLabelTableViewCellID = @"LabelLabelTableViewCellID";

@implementation ConfirmServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self baseSetting];
    [self layoutUI];
}

-(void)baseSetting{
    
    self.navigationItem.title = @"确定服务";
    
}

-(void)backTapClick{
    [super backTapClick];
    [self.delegate addMaterials];
}

-(void)layoutUI{
    
    self.ssehTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT-NAVIGATION_BAR_HEIGHT-50-HOME_INDICATOR_HEIGHT) style:UITableViewStylePlain];
    self.ssehTableView.delegate = self;
    self.ssehTableView.dataSource = self;
    self.ssehTableView.backgroundColor = [UIColor backGroudColorForView];
    self.ssehTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.ssehTableView.showsVerticalScrollIndicator = NO;
    self.ssehTableView.showsHorizontalScrollIndicator = NO;
    [self.ssehTableView registerNib:[UINib nibWithNibName:@"LabelLabelTableViewCell" bundle:nil] forCellReuseIdentifier:LabelLabelTableViewCellID];
    [self.view addSubview:self.ssehTableView];
    
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 50)];
    headerView.backgroundColor = [UIColor whiteColor];
    self.ssehTableView.tableHeaderView = headerView;
    
    UIImageView * imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"repairList"]];
    [headerView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headerView);
        make.left.equalTo(headerView).offset(20);
        make.size.mas_equalTo(CGSizeMake(12, 15));
    }];
    
    UILabel * titleLabel = [UILabel new];
    titleLabel.text = @"维修清单-收费项";
    titleLabel.textColor = RGBColor(51, 51, 51);
    titleLabel.font = [UIFont systemFontOfSize:14];
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.mas_right).offset(5);
        make.centerY.equalTo(headerView);
    }];
    
    UIView * lineView = [UIView new];
    lineView.backgroundColor = [UIColor backGroudColorForView];
    [headerView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(headerView);
        make.height.mas_equalTo(1);
    }];
    
    UIView * foooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 50)];
    foooterView.backgroundColor = [UIColor whiteColor];
    self.ssehTableView.tableFooterView = foooterView;
    
    self.totlePrice = [UILabel new];
    self.totlePrice.textColor = [UIColor roseRed];
    self.totlePrice.text = [self totlePriceForMaterial];
    self.totlePrice.font = [UIFont systemFontOfSize:14];
    self.totlePrice.textAlignment = NSTextAlignmentRight;
    [foooterView addSubview:self.totlePrice];
    [self.totlePrice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(foooterView);
        make.right.equalTo(foooterView.mas_right).offset(-20);
    }];
    
    __weak typeof (self)weakSelf = self;
    
    //底部功能按钮
    UIView * bottomBgView = [UIView new];
    bottomBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomBgView];
    [bottomBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).offset(-HOME_INDICATOR_HEIGHT);
        make.height.mas_equalTo(50);
    }];
    
    for (NSInteger i = 0; i < 3; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i+10;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.layer.borderColor = [UIColor roseRed].CGColor;
        button.layer.borderWidth = 1.0f;
        button.layer.cornerRadius = 4;
        [button setTitleColor:[UIColor roseRed] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(bottomButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        switch (i) {
            case 0:
                [button setTitle:@"确认" forState:UIControlStateNormal];
                break;
            case 1:
                [button setTitle:@"添加" forState:UIControlStateNormal];
                break;
            case 2:
                [button setTitle:@"修改" forState:UIControlStateNormal];
                break;
            default:
                break;
        }
        [bottomBgView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(bottomBgView);
            make.right.equalTo(bottomBgView.mas_right).offset(-(15*(i+1)+70*i));
            make.size.mas_equalTo(CGSizeMake(70, 25));
        }];
        
    }
    
}

-(void)bottomButtonClick:(UIButton *)button{
    
    switch (button.tag) {
        case 10://确认
            [self submitMaterial];
            break;
        case 11://添加
            [self.delegate addMaterials];
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case 12://修改
            [self.delegate changeMaterials];
            [self.navigationController popViewControllerAnimated:YES];
            break;
            
        default:
            break;
    }
    
}

//提交材料
-(void)submitMaterial{
    
    [self showLoading];
    
    NSDictionary * par = @{@"member_id":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserID)],@"member_token":[NSString emptyStr:DEF_PERSISTENT_GET_OBJECT(SsehUserToken)],@"order_id":[NSString emptyStr:self.orderModel.order_id],@"json":[self materalModelToDic]};
    
    [[QYNetManager sharedManager]POST:kInsertMaintailOrderMaterials parameters:par andApiTyp:SsehApiTypGetOrders SuccessBlock:^(id responseObject) {
        
        [self hideLoading];
        
        if ([responseObject[@"status"] isEqualToString:@"ok"]) {
            [self showTipWithTitle:@"添加材料成功!"];
            [self performSelector:@selector(backMain) withObject:nil afterDelay:1.5f];
        }else{
            [self showTipWithTitle:responseObject[@"error"]];
        }
        
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:SsehPoolNetStr];
    }];
    
}

-(void)backMain{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

-(NSString *)materalModelToDic{

    NSMutableArray * modelMarr = [[NSMutableArray alloc]initWithCapacity:0];
    for (NSInteger i = 0; i < self.dataSource.count; i++) {

        SelectdMateralModel * model = self.dataSource[i];
        NSDictionary * dic = @{@"order_material_id":[NSString emptyStr:model.order_material_id],
                               @"material_name":[NSString emptyStr:model.material_name],
                               @"material_count":[NSString emptyStr:model.material_count],
                               @"material_price":[NSString emptyStr:model.material_price]
                               };
        [modelMarr addObject:dic];

    }
    if (kArrayIsEmpty(modelMarr)) {
        return @"";
    }else{
        return [self JsonModel:modelMarr];
    }
}

-(NSString *)JsonModel:(NSMutableArray *)mArr
{
    if ([NSJSONSerialization isValidJSONObject:mArr])
    {
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:mArr options:NSJSONWritingPrettyPrinted error:nil];
        NSString * jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

        return jsonStr;
    }
    return @"";
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.chargeDataSource.count;
    }
    return self.freeDataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LabelLabelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:LabelLabelTableViewCellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        SelectdMateralModel * model = self.chargeDataSource [indexPath.row];
        [cell configData:model];
    }else{
        SelectdMateralModel * model = self.freeDataSource [indexPath.row];
        [cell configData:model];
    }
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0.0001;
    }
    return 50;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * headerView = [UIView new];
    headerView.backgroundColor = [UIColor whiteColor];
    if (section == 1) {
        
        UIImageView * imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"repairList"]];
        [headerView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(headerView);
            make.left.equalTo(headerView).offset(20);
            make.size.mas_equalTo(CGSizeMake(12, 15));
        }];
        
        UILabel * titleLabel = [UILabel new];
        titleLabel.text = @"维修清单-免费项";
        titleLabel.textColor = RGBColor(51, 51, 51);
        titleLabel.font = [UIFont systemFontOfSize:14];
        [headerView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(imageView.mas_right).offset(5);
            make.centerY.equalTo(headerView);
        }];
        
        UIView * lineView = [UIView new];
        lineView.backgroundColor = [UIColor backGroudColorForView];
        [headerView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(headerView);
            make.height.mas_equalTo(1);
        }];
        
    }
    
    return headerView;
    
}

-(NSString *)totlePriceForMaterial{
    
    float price = 0.0f;
    for (NSInteger i = 0; i < self.dataSource.count; i++) {
        SelectdMateralModel * model = self.dataSource[i];
         price += model.material_price.floatValue * model.material_count.floatValue;
    }
    
    return [NSString stringWithFormat:@"总金额： ¥%.2f",price];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
